<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>订单详情</title>
	<meta name="decorator" content="default"/>
	<style type="text/css">
		.table td {
			vertical-align: middle;
		}
		.footer {
			position:fixed; bottom:0; background:#ABABAB; width:100%; height:35px; line-height:32px; z-index:9999; opacity:1;
			filter:alpha(opacity=60); _bottom:auto; _width:100%; _position:absolute;text-align: right;
			_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-
			(parseInt(this.currentStyle.marginTop, 10)||0)-(parseInt(this.currentStyle.marginBottom, 10)||0)));
	    }
	</style>
	<script type="text/javascript">
		var fee = ${fee};//配送费
		var lowFee = ${lowFee};//起送费
		$(document).ready(function() {
			var nodeLen = $(".jbox-button-panel", top.document).length;
			$(".jbox-button-panel", top.document).eq(nodeLen-1).remove();
			if(${toCreate}){
				parent.mainFrame.location.reload();
				document.location="${ctx}/ivm/order/orderDetail?id=${order.id}";
			}
			$("#searchForm").validate({
				submitHandler: function(form){
					var sum = $(".total-amount").html();
					if(sum==undefined){
						sum = 0;
					}
					$("input[id='amount']").val(sum);
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					error.insertAfter(element);
				}
			});
		});
		function page(n,s){
			$("#pageNo").val(n);
			$("#pageSize").val(s);
			$("#searchForm").submit();
        	return false;
        }
        //修改商品数量
		function changeNumber(obj){
			updateNum(obj, 0);
			var price = $(obj).parent().parent().find("input[name='prices']").val();
			var number = $(obj).val();
			$(obj).parent().parent().find("#amounts").html(accMul(price,number));
			$(obj).parent().parent().find("input[name='amounts']").val(accMul(price,number));
			calAmount();
		}
		
		//修改单价
		function changePrice(obj){
			var ff = /^\d+(\.\d+)?$/;
			var val = $(obj).val();
			if(!ff.test(val)){
				alert("请输入整数或小数.");
				$(obj).val("");
			}
			var price = $(obj).val();
			var number = $(obj).parent().parent().find("input[name='numbers']").val();
			$(obj).parent().parent().find("#amounts").html(accMul(price,number));
			$(obj).parent().parent().find("input[name='amounts']").val(accMul(price,number));
			calAmount();
		}
		//修改单价、数量或删除商品时：重新计算总金额
		function calAmount(){
			var totalAmount = 0;
			$("input[name='numbers']").each(function(){
				number = $(this).val();
				price = $(this).parent().parent().find("input[name='prices']").val();
				totalAmount = accAdd(accMul(price,number),totalAmount);
			});
			if(totalAmount<lowFee){
				$(".total-amount").html(accAdd(totalAmount,fee));
			}else{
				$(".total-amount").html(totalAmount);
			}
		}
		//检测商品编号
        function checkProductCode(){
        	if($("#code").val()==""){
				showJBoxMess("请输入商品编号或名称.","error");
				return;
			}
			var obj = $("#code");
			if($(obj).val()!=""){
				//异步保存活动
				$.ajax({
					type: 'post',
					url: '${ctx}/ivm/inventory/checkProductCode',
					data: 'merchantId=${order.merchant.id}&code='+$(obj).val(),
					dataType: 'json',
					success: function(data){
						if(data.status==200){
							var product = data.result;
							var isExists = false;
				        	$("input[id='productCode']").each(function(){
				        		if($(this).val()==product.code){
				        			showJBoxMess("商品"+$(obj).val()+"已存在，请重新输入！","error");
				        			isExists=true;
				        			return false;
				        		}
				        	});
				        	if(isExists) return;
				        	createDeliveryDetail();
						}else{
							showJBoxMess(data.message,"error");
						}
					},
					failure: function(){
						showJBoxMess("操作失败","error");
					}				
				});
			}
		}
		function createDeliveryDetail(){
			//异步手动生成商品采购清单
			$.ajax({
				type: 'get',
				url: '${ctx}/ivm/order/delivery/productDetail',
				data: 'merchantId=${order.merchant.id}&code='+$("#code").val(),
				dataType: 'json',
				success: function(data){
					if(data.status==200){
						var product = data.result;
						var html = '<tr>';
						html += '<td>';
						html += '<input type="hidden" name="detailIds" value="null"/>';
						html += '<input type="hidden" name="products" value="'+product.id+'"/>';
						html += '<input type="hidden" id="productCode" value="'+product.code+'"/>';
						html += '<input type="hidden" name="amounts" value="0"/>';
						html += '<img id="photo" src="${ctx}/download?filePath='+product.logoUrl+'" style="width:95px; height:67px;" />';
						html += '<td>'+product.code+'</td>';
						html += '<td>'+product.name+'</td>';
						html += '<td>'+product.productUnit.name+'</td>';
						html += '<td><input name="prices" value="'+product.price+'" onchange="changePrice(this)" htmlEscape="false" maxlength="20" class="required" style="text-align: center;width:60px;"/>元</td>';
						html += '<td><input name="numbers" value="0" onchange="changeNumber(this)" htmlEscape="false" maxlength="20" min="1" class="required" style="text-align: center;width:60px;"/>'+product.productUnit.name+'</td>';
						html += '<td><span id="amounts">0</span>元</td>';
						html += '<td><a href="javascript:;" onclick="delProduct(this)">删除</a></td>';
						$(".details").append(html);
						$("#code").val("");
					}else{
						showJBoxMess(data.message,"error");
					}
				},
				failure: function(){
					showJBoxMess("操作失败","error");
				}				
			});
		}
		//删除商品
		function delProduct(obj){
			top.$.jBox.defaults.top="28%";
			top.$.jBox.confirm("确认要删除该商品吗",'系统提示',function(v,h,f){
				if(v=='ok'){
					$(obj).parent().parent().remove();
					calAmount();//重新计算订单总金额
					if($(".details").find("tr").length==0){
						var html = "<tr><td>&nbsp;</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><tr>";
						$(".details").append(html);
					}
				}
			},{buttonsFocus:1});
		}
		//保存
		function saveForm(){
			if($("input[name='detailIds']").length==0){
				showJBoxMess("对不起，商品列表不能为空，请添加商品！","error");
				return;
			}else{
				top.$.jBox.defaults.top="28%";
				top.$.jBox.confirm("确认保存吗？",'系统提示',function(v,h,f){
					if(v=='ok'){
						$('#searchForm').submit();
					}
				},{buttonsFocus:1});
			}
		}
	</script>
</head>
<body>
<form:form id="searchForm" modelAttribute="order" action="${ctx}/ivm/order/saveDetail" method="post">
	<form:hidden path="id"/>
	<form:hidden id="amount" path="amount" />
	<!-- 
	<input id="pageNo" name="pageNo" type="hidden" value="${page.pageNo}"/>
	<input id="pageSize" name="pageSize" type="hidden" value="${page.pageSize}"/>
	 -->
	<div style="margin:10px; margin-bottom: 50px;">
		<fieldset class="fieldset">
			<legend class="legend">订单信息</legend>
			<div style="width: 375px;float:left">
				订单号：${order.orderNo }<br>
				下单时间：<fmt:formatDate value="${order.createDate }" pattern="yyyy-MM-dd HH:mm:ss"/><br>
				付款时间：<fmt:formatDate value="${order.payDate}" pattern="yyyy-MM-dd HH:mm:ss"/><br>
				下单人：${order.user.name }<br>
				备注：${order.remarks }
			</div>
			<div>
				要求收货时间：${order.timeSlot.timeText }<br>
				实际送达时间：<fmt:formatDate value="${order.deliveryIndent.deliveryDate }" pattern="yyyy-MM-dd HH:mm:ss"/><br>
				订单总金额：<span class="total-amount">${order.amount }</span>元<br>
				下单人电话：${order.user.mobile }<br>
				<c:if test="${order.orderDiscount != null}"><br>折扣后总金额：${order.disAmount }元</c:if>
			</div>
		</fieldset>
		<fieldset class="fieldset">
			<legend class="legend">收货信息</legend>
			<div>
				收货人：${userAddress.name }<br>
				收货人电话：${userAddress.phone }<br>
				收货地址：${userAddress.detailAddress }
			</div>
		</fieldset>
		<table id="contentTable" class="table table-striped table-bordered table-condensed">
			<thead>
				<tr>
					<th width="95">商品封面</th>
					<th>编号</th>
					<th>名称</th>
					<th>单位</th>
					<th>单价</th>
					<th>数量</th>
					<th>金额</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody class="details">
			<c:forEach items="${orderList}" var="detail">
				<tr>
					<td>
						<input type="hidden" name="detailIds" value="${detail.id }"/>
						<input type="hidden" name="products" value="${detail.product.id }"/>
						<input type="hidden" id="productCode" value="${detail.product.code }"/>
						<input type="hidden" name="amounts" value="${detail.amount }"/>
						<img id="photo" src="${ctx}/download?filePath=${detail.product.logoUrl }" style="width:95px; height:67px;" />
					</td>
					<td>${detail.product.code}</td>
					<td>${detail.product.name}</td>
					<td>${detail.product.productUnit.name}</td>
					<td>
					
						<input name="prices" value="${detail.price }" onchange="changePrice(this)" htmlEscape="false" maxlength="20" class="required" style="text-align: center;width:60px;"/>元
					</td>
					<td>
						<input name="numbers" value="${detail.number }" onchange="changeNumber(this)" htmlEscape="false" maxlength="20" min="1" class="required" style="text-align: center;width:60px;"/>
						${detail.product.productUnit.name}
					</td>
					<td><span id="amounts">${detail.amount}</span>元</td>
					<td><a href="javascript:;" onclick="delProduct(this)">删除</a></td>
				</tr>
			</c:forEach>
			</tbody>
		</table>
		<!-- div class="pagination">${page}</div -->
	</div>
</form:form>
<div class="footer">
	<input type="text" id="code" name="code" htmlEscape="false" maxlength="200" class="input-small" style="margin-bottom: 0px; width: 180px;" placeholder="请输入商品编号或商品名称"/>
	<input class="btn btn-primary" type="button" onclick="checkProductCode()" value="添加商品"/>
	<input id="btnSubmit" class="btn btn-primary" type="button" value="保存" onclick="saveForm()"/>
</div>
</body>
</html>